# -*- coding:utf-8 -*-
# @FileName  :http_request.py
# @Time      :2020/10/24 10:30
# @Author    :zhoujirong

import requests
import traceback
from common.log import Log
from common.utils import create_sign
from common.custom_class import NbDict

class Request:
    def __init__(self,url,params=None,data=None,headers=None,json=None,files=None):
        self.url = url
        self.params = params
        self.data = data
        self.headers = headers
        self.json = json
        self.files = files

    def __get_response(self):
        try:
            result = self.req.json()
        except Exception as e:
            return self.req.text
        else:
            result = NbDict(result)
        return result

    def __get_response_cookie(self):#获取登陆的cookie
        headers = self.req.cookies  # 获得登录的cookie
        cookies = requests.utils.dict_from_cookiejar(headers)
        cookie_dic = dict()  # 定义字典存cookie
        if cookies.get('SHAREJSESSIONID'):
            cookie_dic['Cookie'] = 'SHAREJSESSIONID=%s' % cookies['SHAREJSESSIONID']  # 拼接成{'Cookie':'DCP_SESSIONID=NzJlODg0YzMtMWI2OC00NTQ4LWIxYWUtMDExYTQ2YzQzZWU3'}
        return cookie_dic


    def get(self):
        Log.info("开始发送get请求")
        Log.info("url:【 {} 】,params : 【 {} 】headers:{}",self.url,self.params,self.headers)
        try:
            self.req = requests.get(self.url,params=self.params,headers=self.headers,verify=False)
        except Exception as e:
            Log.error("http请求发送出错，错误信息：{}",traceback.format_exc())
            raise Exception("接口请求不通")

        else:
            return self.__get_response()

    def get_list(self):#返回列表不能转成字典
        Log.info("开始发送get请求")
        Log.info("url:【 {} 】,params : 【 {} 】headers:{}",self.url,self.params,self.headers)
        try:
            self.req = requests.get(self.url,params=self.params,headers=self.headers,verify=False)
        except Exception as e:
            Log.error("http请求发送出错，错误信息：{}",traceback.format_exc())
            raise Exception("接口请求不通")

        else:
            return self.req.json()

    def get_download(self):#下载
        Log.info("开始发送get请求，开始下载/导出...")
        Log.info("url:【 {} 】,params : 【 {} 】headers:{}", self.url, self.params, self.headers)
        try:
            self.req = requests.get(self.url, params=self.params, headers=self.headers, verify=False)
        except Exception as e:
            Log.error("http请求发送出错，错误信息：{}", traceback.format_exc())
            raise Exception("接口请求不通")

        else:
            return self.req.content

    def post_download(self):#下载/导出
        Log.info("开始发送post请求，开始下载/导出...")
        Log.info("url:【 {} 】,params : 【 {} 】headers:{},data:{},json:{},files:{}",
                 self.url,self.params,self.headers,self.data,self.json,self.files)
        try:
            self.req = requests.post(self.url,params=self.params,
                              data=self.data,json=self.json,
                              files=self.files,
                              headers=self.headers,verify=False)
        except Exception as e:
            Log.error("http请求发送出错，错误信息：{}",traceback.format_exc())
            raise  Exception("接口请求不通")
        else:
            return self.req.content

    def post_list(self):#返回列表不能转成字典
        Log.info("开始发送post请求")
        Log.info("url:【 {} 】,params : 【 {} 】headers:{},data:{},json:{},files:{}",
                 self.url,self.params,self.headers,self.data,self.json,self.files)
        try:
            self.req = requests.post(self.url,params=self.params,
                              data=self.data,json=self.json,
                              files=self.files,
                              headers=self.headers,verify=False)
        except Exception as e:
            Log.error("http请求发送出错，错误信息：{}",traceback.format_exc())
            raise  Exception("接口请求不通")
        else:
            return self.req.json()

    def post(self):
        Log.info("开始发送post请求")
        Log.info("url:【 {} 】,params : 【 {} 】headers:{},data:{},json:{},files:{}",
                 self.url,self.params,self.headers,self.data,self.json,self.files)
        try:
            self.req = requests.post(self.url,params=self.params,
                              data=self.data,json=self.json,
                              files=self.files,
                              headers=self.headers,verify=False)
        except Exception as e:
            Log.error("http请求发送出错，错误信息：{}",traceback.format_exc())
            raise  Exception("接口请求不通")
        else:
            return self.__get_response()

    def post_cookie(self):# 获得登录的cookie
        Log.info("开始发送post请求")
        Log.info("url:【 {} 】,params : 【 {} 】headers:{},data:{},json:{},files:{}",
                 self.url,self.params,self.headers,self.data,self.json,self.files)
        try:
            self.req = requests.post(self.url,params=self.params,
                              data=self.data,json=self.json,
                              files=self.files,
                              headers=self.headers,verify=False)
        except Exception as e:
            Log.error("http请求发送出错，错误信息：{}",traceback.format_exc())
            raise  Exception("接口请求不通")
        else:
            return self.__get_response_cookie()

if __name__ == "__main__":
    url = "https://oapi.dingtalk.com/robot/send?access_token=74f3028e80a522f28733f3dab9f0d1060f77a5749da637c531bd999f3828ec9b"
    sign = create_sign()
    msg = "hhhhhhhh "
    data = {
        "msgtype": "text",
        "text": {
            "content": msg
        },
        "at": {
            "atMobiles": [
                "15620922243",
                "13011823376",
                "13240224523",
                "15901399089"
            ],
            "isAtAll": False
        }
    }
    r = Request(url,params=sign,json=data)
    result = r.post()
    print(result)